$(function () {
    //全局参数
    var plynDatas; //行政区划
    var plyn, marker;
    var mapAreaCode = '330000'; //区划关键点
    var trgetolddata, trgetnewdata, trgetold, trgetnew;
    var overlayGroups; //全部覆盖物
    var myGDMap = new AMap.Map('map', {
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        zoom: 7,
        pitch: 45,
        mapStyle: "amap://styles/dark",
        rotation: 0,
        // viewMode:'3D',//开启3D视图,默认为关闭
        buildingAnimation: true, //楼块出现是否带动画
        expandZoomRange: true,
        center:[120.153576,29.289523]
        // zooms: [7, 20],
        // center: [120.153576, 30.287459]

    });
    //地图指标类型
    var mapTypes = {
        main:[{name:'安薪指数',value:'azzs'}],
        qxyj:[
            {name:'预警在办',value:'zds'},
            {name:'预警逾期',value:'yqs'},
        ],
        ldjf:[
            {name:'纠纷化解在办',value:'zb'},
            {name:'万人成案率',value:'wrcal'},
            {name:'调解成功率',value:'tjcgl'},
        ],
        qxxs:[
            {name:'部线索',value:'bxs'},
            {name:'省线索',value:'sxs'}
        ],
        gzjg:[{name:'工资监管',value:''}],
    }
    //弹窗表头
    var topTableColsDatas = [
        [{
                field: 'aab004',
                title: '企业名称',
                event: 'viewCompany'
            },
            {
                field: 'aac003',
                title: '统一社会信用代码',
            },
            {
                field: 'aab013',
                title: '法人代表',
            },
            {
                field: 'comtypes',
                title: '企业分类',
            },
            {
                field: 'aab301s',
                title: '管辖',
            }
        ]
    ];
    AMap.plugin([
        'AMap.ToolBar',
    ], function () {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        myGDMap.addControl(new AMap.ToolBar({
            // 简易缩放模式，默认为 false
            liteStyle: false
        }));
    })
    
    initMap();//初始化地图调用
    $('.tablist .tab_item').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        setMapTypeSelects();
    })
    
    function setMapTypeSelects(){// 动态生成地图指标
        var type = $('.tablist .tab_item.active').attr('data-maptype');
        var selectDatas = mapTypes[type],html='';
        $.each(selectDatas,function(i,item){
            html += `<div class="tab_content_item">
                        <input type="radio" name="mapType" checked group="mapType" value="${item.value}" /><i></i>
                        <span class="map_type_name">${item.name}</span>
                    </div>`
        });
        $('.chose_box').html(html);
        $('.tab_content_item [name="mapType"]').change(function(){
            // getPoints();
            getPLYN();
        });
        // $('.tab_content_item').eq(0).find('[name="mapType"]').attr("checked",true);
        $('.tab_content_item').eq(0).find('[name="mapType"]').click();
        

    }
    
    function initMap() {//初始化地图
        setMapTypeSelects();
        getPLYN();
        myGDMap.on('zoomchange', mapZoom);
    }
    
    function getPLYN(callback) {//加载区划
        myGDMap && myGDMap.clearMap();
        $.ajax({
            type: 'get',
            url: '../json/' + mapAreaCode + '.json',
            success: function (res) {
                plynDatas = res.map(aoi => {
                    var regEx = /\s+/g;
                    var wkt = aoi.wkt.replace(regEx, ' ').split(',')
                    aoi.wkt = wkt.map(pair => pair.split(' '))
                    return aoi;
                });
                setMapPlyn(plynDatas);
                getPoints();
                callback && callback();
            }
        })
    }
    
    function mapZoom(e) {//监听地图缩放
        var zoom = myGDMap.getZoom();
        if (zoom == 7) {
            mapAreaCode = '330000';
            myGDMap.setZoomAndCenter(7, [120.153576,29.289523])
            $('.map_tit').html('浙江省')
            getPLYN();
        } else if (zoom == 9) {

        }
    }
    
    function getPoints() {//获取地图点数据
        myGDMap.off('click')
        var type = $('.tablist .tab_item.active').attr('data-maptype');
        var subType = $('.tab_content_item [name="mapType"]:checked').val();
        var subTypeName = $('.tab_content_item [name="mapType"]:checked').siblings('.map_type_name').html();
        var params = {
            aab301: mapAreaCode,
            type: (type == 'main'?'':type),
            style: (subType == 'azzs'?'':subType)
        }
        $.ajax({
            type: "get",
            url: ajaxUrl + '/zjax/admin/zjax/mapData',
            data: params,
            async: true,
            success: function (res) {
                setPoints(res.data,type,subType,subTypeName);
            }
        });
    }

    function setPoints(datas,type,subType,subTypeName) {//添加地图点
        datas = datas.filter(item => item.aab301 != mapAreaCode)
        $.each(datas, function (i, item) {
            var html = `<div class="map_text_con ${getPointClass(item.value,type,subType)}">
								<div class="effect_scatter">
									<div class="effect_circle circle"></div>
									<div class="effect_circle effect_circle1"></div>
									<div class="effect_circle effect_circle2"></div>
									<div class="effect_circle effect_circle3"></div>
									<!-- <div class="effect_circle effect_circle4"></div> -->
								</div>
								<div class="area_box">
									<div class="text">${item.ctname}</div>
								</div>
								<div class="num_box num white">${item.value}</div>
								<div class="name_box">${subTypeName}</div>
							</div>`
            // let html = '<div class="mapIcon mapIcon">' + item.value + '<span class="dw">' + item.ctname + '</span></div>';
            var index = plynDatas.map(item => item.areaCode).indexOf(item.aab301);
            var lnglat = {
                lng: plynDatas[index].x,
                lat: plynDatas[index].y
            }
            marker = new AMap.Marker({
                // position: new AMap.LngLat(item.lng-0, item.lat-0),
                // content: item.ctname,
                position: new AMap.LngLat(lnglat.lng - 0, lnglat.lat - 0),
                // 将 html 传给 content
                content: html,
                // 以 icon 的 [center bottom] 为原点
                offset: new AMap.Pixel(-18, -15),
                data: item
            });
            myGDMap.add(marker);
        })
    }
    function getPointClass(value,type,subType){// 转换点样式
        /**
        main:[{name:'安薪指数',value:'axzs'}],
        qxyj:[
            {name:'预警在办',value:'zds'},
            {name:'预警逾期',value:'yqs'},
        ],
        ldjf:[
            {name:'纠纷化解在办',value:'zb'},
            {name:'万人成案率',value:'wrcal'},
            {name:'调解成功率',value:'tjcgl'},
        ],
        qxxs:[
            {name:'部线索',value:'bxs'},
            {name:'省线索',value:'sxs'}
        ],
        gzjg:[{name:'工资监管',value:''}],
         */
        if(type == 'main'){// 安薪指数 默认蓝色，低于90%的用红色
            if(value<90){
                return 'map_text_con_red'
            }else{
                return '';
            }
        }else if (type == 'qxyj'){// 预警在办 红、橙、黄三色
            if(subType == 'zds'){
                if(value<90){
                    return 'map_text_con_red'
                }else if(value>=90 && value<98){
                    return 'map_text_con_yellow';
                }else{
                    return 'map_text_con_green';
                }
            }else{
                return '';
            }
            
        }else if (type == 'ldjf'){// 纠纷化解在办，使用红、橙、黄三色
            if(subType == 'zb'){
                if(value<90){
                    return 'map_text_con_red'
                }else if(value>=90 && value<98){
                    return 'map_text_con_yellow';
                }else{
                    return 'map_text_con_green';
                }
            }else{
                return '';
            }
        }else if (type == 'qxxs'){// 使用红、橙、黄三色
            if(value<90){
                return 'map_text_con_red'
            }else if(value>=90 && value<98){
                return 'map_text_con_yellow';
            }else{
                return 'map_text_con_green';
            }
        }else if (type == 'gzjg'){
            return '';
        }

    }
    function setMapPlyn(datas) {// 生成地图区块
        $.each(datas, function (i, item) {
            // var index = plynDatas.map(item=>item.aoiid).indexOf(item.aab301);
            // if(index > -1){
            let colors = 'rgba(57,92,115,1)'
            plynItem = item;
            plynItem.areaCode = item.aoiid;
            plyn = new AMap.Polygon({
                bubble: true,
                fillOpacity: 0.6,
                strokeWeight: 1,
                fillColor: colors,
                path: plynItem.wkt,
                map: myGDMap,
                data: plynItem,
                cont: [plynItem.x, plynItem.y]
            })
            // }
            AMap.event.addListener(plyn, 'click', function (e) { //添加点击事件,传入对象名，事件名，回调函数
                areaClick(e.target.w.data, e.target.w.cont, e)
            })
        });
    }
    
    function areaClick(data, cont, ev) {//地区点击事件
        mapAreaCode = data.areaCode;
        var mapLevel = getAreaLevel(mapAreaCode);
        var zoom = myGDMap.getZoom();
        var px = ev.target.setOptions({
            fillColor: 'rgba(255,255,255,1)'
        });
        // 拾取所在位置的行政区
        let colors = 'rgba(57,92,115,1)'
        trgetolddata = trgetnewdata
        trgetold = trgetnew;

        if (zoom >= 7 && zoom <= 20) {
            if (mapLevel == 0) {
                myGDMap.setZoomAndCenter(7, [120.153576,29.289523])
            } else if (mapLevel == 1) {
                myGDMap.setZoomAndCenter(9, [data.x, data.y])
                $('.back').show();
                getPLYN();
            } else if (mapLevel == 2) {
                $('.map_tit').html(data.ctname);
                trgetnewdata = data;
                trgetnew = ev.target;
                mapAreaCode = data.areaCode
                trgetold.setOptions({
                    fillColor: colors
                })
                myGDMap.setZoomAndCenter(11, [data.x, data.y])
            }

        }

    }
    
    function iconClick(data) {//地区点击事件
        var item = $('input:radio[name="radio"]:checked').val();
        if (item == 'zdqy') {
            $('.zezhao').show();
            $$.alertTable({
                title: '重点监控企业',
                colsData: topTableColsDatas,
                url: ajaxUrl + '/api/admin/display/dtjgBaseDataList', //请求接口
                where: {
                    keymonitor: 1,
                    aab301: data.aab301
                },
                pageProp: {
                    limit: 10
                },
                rowClickFun: function (obj) {
                    // $$.xqtanc({
                    //     url: ajaxUrl + '/api/admin/display/dtjgBaseDatadetails',
                    //     pream: {
                    //         aab001: obj.data.aab001
                    //     },
                    //     title: '单位详情',
                    //     colsdata: xqtable[0]
                    // })
                }
            });
        }

    }

    function getAreaLevel(areaCode) {//获取地图层级
        areaCode += "";
        if (areaCode.length > 6) {
            return 3;
        } else if (areaCode.length == 6) {
            if (areaCode.substr(2) == "0000") {
                return 0;
            } else if (areaCode.substr(4) == "00") {
                return 1;
            } else {
                return 2;
            }
        }
    }
    $('.back').click(function () {
        mapAreaCode = '330000';
        myGDMap.setZoomAndCenter(7, [120.153576,29.289523])
        $(this).hide();
        $('.map_tit').html('浙江省')
        getPLYN();
    })
    //回归定位点
    $('.backToOriginal').click(function () {
        mapAreaCode = '330000';
        myGDMap.setZoomAndCenter(7, [120.153576,29.289523]);
        $('.map_tit').html('浙江省');
        getPLYN();
    })
    //增加
    $('.add').click(function () {
        var zoom = myGDMap.getZoom();
        if (zoom < 20) {
            zoom++;
        }
        myGDMap.setZoom(zoom);
    })
    //减少
    $('.del').click(function () {
        var zoom = myGDMap.getZoom();
        if (zoom > 7) {
            zoom--;
        }
        myGDMap.setZoom(zoom);
    })
})